package UDPEcho;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UDPEchoCline1 {
    //由于UDP是无连接的，所以在客户端中需要保存服务器的ip和端口号
    private DatagramSocket socket = null;
    private String severIp;
    private int severPort;

    public  UDPEchoCline1(String severIp,int severPort) throws SocketException {
        this.severIp = severIp;
        this.severPort = severPort;
        //此处的socket直接使用系统分配的端口号即可
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.print("->");
            if (!scanner.hasNext()){
                break;
            }
            //读取输入的请求并发送
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(severIp),severPort);
            socket.send(requestPacket);
            //接收服务器返回响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            //打印响应
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPEchoCline1 udpEchoCline1 = new UDPEchoCline1("127.0.0.1",6060);
        udpEchoCline1.start();
    }
}
